package com.example.springbootdemo.controller;

import com.example.springbootdemo.crypt.BCryptPasswordEncoder;
import com.example.springbootdemo.entity.SysUser;
import com.example.springbootdemo.model.CommonModel;
import com.example.springbootdemo.service.ISysUserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

// @CrossOrigin(origins = "*")
@RestController
public class LoginController {

    private ISysUserService sysUserService;

    public LoginController(ISysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    @PostMapping("/login")
    public CommonModel login(String username, String password, HttpSession session) {
        SysUser sysUser = sysUserService.getSysUserByName(username);
        CommonModel commonModel = new CommonModel();
        // 根据用户名没有对应的用户
        if(null == sysUser) {
            commonModel.setCode(-1);
            commonModel.setMsg("用户名或者密码错误.");
        }else {  //表示用户存在
            String cryptPassword = sysUser.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            // matches() 是将原生密码和数据库密码(是用户注册时加密之后放入到数据库的密码)比较
            boolean isMatch = bCryptPasswordEncoder.matches(password, cryptPassword);
            if(isMatch) {
                session.setAttribute("userInfo", sysUser);
                commonModel.setCode(1);
                commonModel.setDatas(session.getId());
                commonModel.setMsg("success");
            }else {
                commonModel.setCode(-1);
                commonModel.setMsg("用户名或者密码错误.");
            }
        }
        return commonModel;
    }
}
